package cn.iocoder.yudao.module.system.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {
    private static final String ALGORITHM = "AES";
    private static final String secretKey = "xiaoluoaaaaaluoluoluo";

    // 加密方法
    public static String aesEncrypt(String data) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedBytes); // 使用 Base64 编码密文
    }

    // 解密方法
    public static String aesDecrypt(String encryptedData) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedData); // 先解码 Base64
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, "UTF-8");
    }

    public static void main(String[] args) {
        try {
            String secretKey = "xiaoluoaaaaaluoluoluo"; // 16 字节密钥
            String originalText = "123456";

            // 加密
//            String encryptedText = aesEncrypt(originalText);
//            System.out.println("Encrypted Text: " + encryptedText);

            // 解密
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
